package com.pureut.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.quality.domain.*;
import com.pureut.quality.domain.dto.PatrolSampleInspectionDto;
import com.pureut.quality.domain.dto.SampleInspectionDto;
import com.pureut.quality.domain.vo.*;
import com.pureut.quality.mapper.*;
import com.pureut.quality.service.*;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 巡检样本信息表实现层
 * Author:C
 * Date:2023/02/13 14:20
 * @DESC
 */
@Service
public class QualityPatrolSampleInformationServiceImpl extends ServiceImpl<QualityPatrolSampleInformationMapper, QualityPatrolSampleInformation> implements QualityPatrolSampleInformationService {

    @Resource
    QualityPatrolSampleInformationMapper qualityPatrolSampleInformationMapper;

    @Resource
    QualityPatrolInspectionDocumentService qualityPatrolInspectionDocumentService;

    @Resource
    QualityPatrolBadSampleService qualityPatrolBadSampleService;

    @Resource
    QualityPatrolTemporaryMapper qualityPatrolTemporaryMapper;

    @Resource
    QualityPatrolTemporaryService qualityPatrolTemporaryService;

    @Resource
    QualityProductionFreezeService qualityProductionFreezeService;

    @Resource
    StorageFegin storageFegin;

    @Resource
    FeignProductionService feignProductionService;

    @Resource
    PublicProjectMapper publicProjectMapper;

    @Resource
    QualityPatrolInspectionDocumentMapper qualityPatrolInspectionDocumentMapper;

    /**
     * 巡检样本信息列表
     *
     * @param patrolInspectionSheetNo
     * @return
     */
    @Override
    public List<PatrolSampleInspectionDto> getPatrolSampleInformationList(String patrolInspectionSheetNo) {
        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //不良等级
        List<SysDictData> badLevelArray = DictUtils.getDictCache("quality_bad_level");
        Map<String, String> badLevelMap = badLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

//        List<PublicProject> publicProjectList = publicProjectMapper.selectList(new QueryWrapper<PublicProject>().lambda().eq(PublicProject::getInspectionSheetNo, patrolInspectionSheetNo));
//        if (publicProjectList.size() < 1) {
//            throw new GlobalException("未找到配置的项目");
//        }
        QualityPatrolInspectionDocument qualityPatrolInspectionDocument = qualityPatrolInspectionDocumentMapper.selectOne(new QueryWrapper<QualityPatrolInspectionDocument>().lambda().eq(QualityPatrolInspectionDocument::getPatrolInspectionNo, patrolInspectionSheetNo));

        List<String> strings = Arrays.asList(qualityPatrolInspectionDocument.getItemIds().split(","));
        List<PublicProject> publicProjectList = publicProjectMapper.selectList(new QueryWrapper<PublicProject>().lambda().in(PublicProject::getItemId, strings));


        List<PatrolSampleInspectionDto> informationList = qualityPatrolSampleInformationMapper.getPatrolInformationList(patrolInspectionSheetNo);

        for (PatrolSampleInspectionDto entity : informationList) {
//            List<ActualValueVo> actualValueList = entity.getActualValueList();
            List<ActualValueVo> actualValueList = new ArrayList<>();
            List<String> averageValues = Arrays.asList(entity.getActualValue().split(","));
            for (String averageValue : averageValues) {
                ActualValueVo actualValueVo = new ActualValueVo();
                actualValueVo.setActualValue(averageValue);
                actualValueList.add(actualValueVo);
            }

            for (PublicProject detail : publicProjectList) {
                if (entity.getItemId().equals(detail.getItemId())) {
                    entity.setItemLowerLimit(detail.getItemLowerLimit());
                    entity.setItemUpperLimit(detail.getItemUpperLimit());
                    entity.setItemName(detail.getItemName());
                    //管控方式
                    entity.setItemControlModeDict(controlModeMap.get(String.valueOf(detail.getItemControlMode())));
                    entity.setItemCheckContent(detail.getItemCheckContent());
                }
            }
            entity.setActualValueList(actualValueList);
//            //管控方式
//            entity.setItemControlModeDict(controlModeMap.get(entity.getItemControlMode()));
            //检验结果
            entity.setInspectionResultsDict(resultsMap.get(entity.getInspectionResults()));
            //不良等级
            entity.setBadGradeDict(badLevelMap.get(entity.getBadGrade()));
        }
        return informationList;
    }

    /**
     * 保存（小保存）
     *
     * @param patrolSampleAddVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(PatrolSampleAddVo patrolSampleAddVo) {

        List<PatrolSampleInspectionVo> sampleInspectionList = patrolSampleAddVo.getSampleInspectionList();

        List<QualityPatrolSampleInformation> qualityPatrolSampleInformationList = new ArrayList<>();
        //获取巡检单数据
        QualityPatrolInspectionDocument qualityPatrolInspectionDocument = qualityPatrolInspectionDocumentService.getById(patrolSampleAddVo.getId());
        for (PatrolSampleInspectionVo entity : sampleInspectionList) {
            QualityPatrolSampleInformation qualityPatrolSampleInformation = new QualityPatrolSampleInformation();
            qualityPatrolSampleInformation.setSampleNumber(patrolSampleAddVo.getMaterialNumber())
                    .setItemId(entity.getId())
                    .setActualValue(entity.getActualValue())
                    .setAverageValue(String.valueOf(entity.getAverageValue()))
                    .setInspectionResults(entity.getInspectionResults())
                    .setBadId(entity.getBadId())
                    .setPatrolInspectionSheetNo(qualityPatrolInspectionDocument.getPatrolInspectionNo());
            qualityPatrolSampleInformationList.add(qualityPatrolSampleInformation);
        }
        saveBatch(qualityPatrolSampleInformationList);
        //保存样本检验结果
        QualityPatrolBadSample qualityPatrolBadSample = new QualityPatrolBadSample();
        qualityPatrolBadSample.setSampleNumber(patrolSampleAddVo.getMaterialNumber())
                .setInspectionBy(SecurityUtils.getUsername())
                .setInspectionTime(new Date())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId())
                .setPatrolInspectionSheetNo(qualityPatrolInspectionDocument.getPatrolInspectionNo());
        //获取不良数量
        List<QualityPatrolSampleInformation> collect = qualityPatrolSampleInformationList.stream().filter(entity -> !(entity.getBadId() == null)).collect(Collectors.toList());
        qualityPatrolBadSample.setDefectiveQuantity(Long.parseLong(String.valueOf(collect.size())));
        //获取检验结果
        List<PatrolSampleInspectionVo> collect1 = sampleInspectionList.stream().filter(entity -> entity.getIsAverage() == 1).collect(Collectors.toList());
        boolean isAll = true;
        for (PatrolSampleInspectionVo entity : collect1) {
            if (entity.getInspectionResults() == 2) {
                isAll = false;
                break;
            }
        }
        if (isAll) {
            qualityPatrolBadSample.setInspectionResults(1);
        } else {
            qualityPatrolBadSample.setInspectionResults(2);
        }
        qualityPatrolBadSampleService.save(qualityPatrolBadSample);
        //判断样品的检验结果，如果不合格就进入到冻结数据
        if (qualityPatrolBadSample.getInspectionResults() == 2) {
            QualityPatrolTemporary qualityPatrolTemporary = qualityPatrolTemporaryMapper.selectOne(new QueryWrapper<QualityPatrolTemporary>()
                    .lambda()
                    .eq(QualityPatrolTemporary::getMaterialNumber, qualityPatrolBadSample.getSampleNumber())
                    .eq(QualityPatrolTemporary::getPatrolInspectionSheetNo,qualityPatrolInspectionDocument.getPatrolInspectionNo()));

            //不合格,进行冻结
            QualityProductionFreeze qualityProductionFreeze = new QualityProductionFreeze();
            qualityProductionFreeze.setStatus(1)
                    .setMaterialGrade(1)
                    .setMaterialCode(qualityPatrolTemporary.getMaterialCode())
                    .setProductionLine(qualityPatrolInspectionDocument.getProductionLine())
                    .setOrderNo(qualityPatrolInspectionDocument.getOrderNo())
                    .setFrozenBy(SecurityUtils.getUsername())
                    .setFrozenTime(new Date())
                    .setProductNumber(qualityPatrolBadSample.getSampleNumber())
                    .setCreateTime(new Date())
                    .setDeptId(SecurityUtils.getDeptId())
                    .setNetWeight(String.valueOf(qualityPatrolTemporary.getNetWeight()));
            qualityProductionFreezeService.save(qualityProductionFreeze);
            //同时修改仓库或者线边仓的物料冻结标识
            //冻结仓库物料
            String materialNumber = qualityPatrolTemporary.getMaterialNumber();
            storageFegin.updateStatusThaw(materialNumber);
            //冻结线边仓物料
            feignProductionService.updateStatusThaw(materialNumber);
        }
        //修改检验单据状态
        qualityPatrolInspectionDocument.setStatus(2);
        qualityPatrolInspectionDocumentService.updateById(qualityPatrolInspectionDocument);
        //修改来料信息状态
        QualityPatrolTemporary qualityPatrolTemporary = qualityPatrolTemporaryMapper.selectOne(new QueryWrapper<QualityPatrolTemporary>().lambda().eq(QualityPatrolTemporary::getMaterialNumber, patrolSampleAddVo.getMaterialNumber()).eq(QualityPatrolTemporary::getPatrolInspectionSheetNo, qualityPatrolInspectionDocument.getPatrolInspectionNo()));
        qualityPatrolTemporary.setInspectionMark(1);
        qualityPatrolTemporary.setInspectionResults(qualityPatrolBadSample.getInspectionResults());

        return qualityPatrolTemporaryService.updateById(qualityPatrolTemporary);
    }

    /**
     * 保存
     *
     * @param patrolAddDocumentVo
     * @return
     */
    @Override
    public boolean addDocument(PatrolAddDocumentVo patrolAddDocumentVo) {
        QualityPatrolInspectionDocument byId = qualityPatrolInspectionDocumentService.getById(patrolAddDocumentVo.getId());
        //查询是否有检验的样品信息
        List<QualityPatrolSampleInformation> qualityPatrolSampleInformations = qualityPatrolSampleInformationMapper.selectList(new QueryWrapper<QualityPatrolSampleInformation>().lambda().eq(QualityPatrolSampleInformation::getPatrolInspectionSheetNo, byId.getPatrolInspectionNo()));
        if (qualityPatrolSampleInformations.size() == 0) {
            throw new GlobalException("至少有一条检验数据才能进行此操作");
        }
        byId.setStatus(3);
        byId.setInspectTime(new Date());
        return qualityPatrolInspectionDocumentService.updateById(byId);
    }
}
